<?php
// keywords.php - 从MySQL随机返回1条 is_read=0 的关键词，并立即标记为 is_read=1

declare(strict_types=1);
ini_set('display_errors', '1');
error_reporting(E_ALL);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

date_default_timezone_set('Asia/Shanghai');

$configPath = __DIR__ . '/config.php';
if (!file_exists($configPath)) {
    http_response_code(500);
    echo json_encode(['code' => 1, 'msg' => '缺少配置文件config.php', 'data' => null], JSON_UNESCAPED_UNICODE);
    exit;
}
$config = require $configPath;

$keywords = [];

// 仅从MySQL取随机1条 is_read=0
try {
    $dsn = sprintf('mysql:host=%s;port=%d;dbname=%s;charset=%s',
        $config['db_host'], (int)$config['db_port'], $config['db_name'], $config['db_charset']
    );
    $pdo = new PDO($dsn, $config['db_user'], $config['db_pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$config['db_charset']}"
    ]);

    // 直接取出一条 is_read=0 的记录，按 id ASC 排序
    $sqlOne = 'SELECT `id`, `keyword` FROM `keyword` WHERE `is_read` = 0 ORDER BY `id` ASC LIMIT 1';
    $stmt = $pdo->prepare($sqlOne);
    $stmt->execute();
    $one = $stmt->fetch();

    if ($one && !empty($one['keyword'])) {
        $kw = trim((string)$one['keyword']);
        if ($kw !== '') {
            // 标记为已读
            try {
                $up = $pdo->prepare('UPDATE `keyword` SET `is_read` = 1, `update_time` = CURRENT_TIMESTAMP WHERE `id` = :id');
                $up->execute([':id' => (int)$one['id']]);
            } catch (Throwable $e) {
                // 不影响返回
            }
            $keywords = [$kw];
        }
    }

    echo json_encode([
        'code' => 0,
        'msg' => 'ok',
        'data' => [
            'keywords' => $keywords,
            'source' => $config['source'] ?? 'wm745640'
        ]
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['code' => 1, 'msg' => '数据库错误: ' . $e->getMessage(), 'data' => null], JSON_UNESCAPED_UNICODE);
} 